import React, { PureComponent } from "react";
import {
  Table, Button, Popconfirm, Form,
} from 'antd';
import EditableCell from "./EditableCell";

const EditableContext = React.createContext();
const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableTable extends PureComponent {
  constructor(props) {
    super(props);
    this.columns = [{
      title: '参数编码',
      dataIndex: 'code',
      width: '40%',
      editable: true,
    }, {
      title: '参数值',
      dataIndex: 'nub',
      editable: true,
      width: '40%',
    }, {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        const { dataSource=[]}=this.props
        return(dataSource.length >= 1
          ? (
            <Popconfirm title="确定删除此参数吗？" onConfirm={() => this.handleDelete(record.key)}>
              <a>删除</a>
            </Popconfirm>
          ) : null
      )},
    }];
  }

  handleDelete = (key) => {
    const { dataSource, handleTableSourceChange}=this.props
    handleTableSourceChange(dataSource.filter(item => item.key !== key))
  }

  handleAdd = () => {
    const { count, dataSource, handleTableSourceChange } = this.props;
    const newData = {
      key: count,
      code: `${count}号参数`,
      nub: `${ count }`,
    };
    handleTableSourceChange([...dataSource, newData], count + 1,)
  }

  handleSave = (row) => {
    const { handleTableSourceChange, dataSource}=this.props
    const newData = [...dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    handleTableSourceChange(newData)
  }

  render() {
    const { dataSource } = this.props;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <div>
        <div style={{display:"flex",justifyContent:"space-between"}}>        
          <span>配置启动参数</span>
          <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
            添加
          </Button>
        </div>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          pagination={{ pageSize: 6 }}
        />
      </div>
    );
  }
}

export default EditableTable;